package com.army.study;

import com.army.study.common.PermissionBridge;
import com.army.study.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class MainAbility extends Ability {
    private static final int EVENT_PERMISSION_GRANTED = 0x0000023;
    private static final int EVENT_PERMISSION_DENIED = 0x0000024;
    private static final int PERMISSION_REQUEST_CODE = 0;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());

        requestPermission();
    }

    // 向用户申请相关权限的授权
    private void requestPermission() {
        String[] permissions = {
          // 计步器权限
                SystemPermission.ACTIVITY_MOTION
        };

        List<String> permissionFiltereds = Arrays.stream(permissions)
                // 过滤出没有被授权
                .filter(permission -> verifySelfPermission(permission) != IBundleManager.PERMISSION_GRANTED)
                .collect(Collectors.toList());
        // 如果为空, 说明都授权了
        if (permissionFiltereds.isEmpty()) {
            PermissionBridge.getHandler().sendEvent(EVENT_PERMISSION_GRANTED);
            return;
        }
        // 向用户申请相关权限的授权提示
        requestPermissionsFromUser(permissionFiltereds.toArray(new String[permissionFiltereds.size()]), PERMISSION_REQUEST_CODE);
    }

    @Override
    public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
        if (null == permissions || 0 == permissions.length || null == grantResults || 0 == grantResults.length) {
            return;
        }
        for (int grantResult : grantResults) {
            if (grantResult != IBundleManager.PERMISSION_GRANTED) {
                PermissionBridge.getHandler().sendEvent(EVENT_PERMISSION_DENIED);
                terminateAbility();
                return;
            }
        }
        PermissionBridge.getHandler().sendEvent(EVENT_PERMISSION_GRANTED);
    }

    @Override
    public void onStop() {
        super.onStop();
    }
}
